<template>
  <div class="login-form">
    <div class="login-header">
      <h1 class="login-title">欢迎登录</h1>
      <p class="login-subtitle">请输入您的账号信息</p>
    </div>

    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form-content" size="large"
      @submit.prevent="handleSubmit">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" :disabled="isLoading"
          @keyup.enter="handleSubmit" />
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
          :disabled="isLoading" show-password @keyup.enter="handleSubmit" />
      </el-form-item>

      <el-form-item>
        <div class="login-options">
          <el-checkbox v-model="loginForm.rememberMe" :disabled="isLoading">
            记住我
          </el-checkbox>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="login-button" :loading="isLoading" :disabled="!isFormValid"
          @click="handleSubmit">
          {{ isLoading ? '登录中...' : '登录' }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 错误提示 -->
    <el-alert v-if="errorMessage" :title="errorMessage" type="error" class="login-error" show-icon :closable="false" />
    
    <!-- 注册链接 -->
    <div class="login-footer">
      <p>
        还没有账号？
        <router-link to="/register" class="register-link">立即注册</router-link>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElCheckbox, ElAlert, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useAuthStore } from '../stores/auth'
import type { LoginRequest } from '../types'

// Props and Emits
interface Props {
  autoFocus?: boolean
}

interface Emits {
  (e: 'login-success'): void
  (e: 'login-error', error: string): void
}

const props = withDefaults(defineProps<Props>(), {
  autoFocus: true
})

const emit = defineEmits<Emits>()

// Store
const authStore = useAuthStore()

// Form ref
const loginFormRef = ref<FormInstance>()

// Form data
const loginForm = ref<LoginRequest>({
  username: '',
  password: '',
  rememberMe: false
})

// Form validation rules
const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度应在 6 到 50 个字符', trigger: 'blur' }
  ]
}

// Computed
const isLoading = computed<boolean>(() => authStore.isLoading)
const errorMessage = computed<string | null>(() => authStore.authError)
const isFormValid = computed<boolean>(() => {
  return loginForm.value.username.trim() !== '' &&
    loginForm.value.password.trim() !== '' &&
    !isLoading.value
})

// Methods
const handleSubmit = async () => {
  if (!loginFormRef.value) return

  try {
    // Validate form
    const isValid = await loginFormRef.value.validate()
    if (!isValid) return

    // Clear previous errors
    authStore.clearError()

    // Attempt login
    const success = await authStore.login(loginForm.value)

    if (success) {
      ElMessage.success('登录成功')
      emit('login-success')
    } else {
      emit('login-error', errorMessage.value || '登录失败')
    }
  } catch (error) {
    console.error('Login form submission error:', error)
    const errorMsg = error instanceof Error ? error.message : '登录过程中发生未知错误'
    emit('login-error', errorMsg)
  }
}

const resetForm = () => {
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
  authStore.clearError()
}

const focusFirstInput = () => {
  // Focus on username input after component is mounted
  const usernameInput = document.querySelector('.login-form input[placeholder="请输入用户名"]') as HTMLInputElement
  if (usernameInput && props.autoFocus) {
    usernameInput.focus()
  }
}

// Lifecycle
onMounted(() => {
  focusFirstInput()
})

// Expose methods for parent component
defineExpose({
  resetForm,
  focusFirstInput
})
</script>

<style scoped lang="scss">
.login-form {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  @media (max-width: 768px) {
    max-width: 100%;
    margin: 0;
    padding: 1.5rem;
    border-radius: 0;
    box-shadow: none;
  }
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;

  .login-title {
    font-size: 1.5rem;
    font-weight: 600;
    color: #303133;
    margin: 0 0 0.5rem 0;
  }

  .login-subtitle {
    font-size: 0.875rem;
    color: #909399;
    margin: 0;
  }
}

.login-form-content {
  .el-form-item {
    margin-bottom: 1.5rem;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-input {
    height: 48px;

    :deep(.el-input__inner) {
      height: 48px;
      line-height: 48px;
      font-size: 1rem;
    }
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .el-checkbox {
    :deep(.el-checkbox__label) {
      font-size: 0.875rem;
      color: #606266;
    }
  }
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 1rem;
  font-weight: 500;
  border-radius: 6px;
}

.login-error {
  margin-top: 1rem;

  :deep(.el-alert__title) {
    font-size: 0.875rem;
  }
}

.login-footer {
  text-align: center;
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid #f0f0f0;

  p {
    color: #909399;
    font-size: 0.875rem;
    margin: 0;
  }

  .register-link {
    color: #409eff;
    text-decoration: none;
    font-weight: 500;

    &:hover {
      text-decoration: underline;
    }
  }
}

// Loading state styles
.login-form.loading {

  .el-input,
  .el-checkbox,
  .el-button {
    pointer-events: none;
  }
}

// Responsive design
@media (max-width: 480px) {
  .login-form {
    padding: 1rem;
  }

  .login-header {
    margin-bottom: 1.5rem;

    .login-title {
      font-size: 1.25rem;
    }
  }

  .login-form-content {
    .el-form-item {
      margin-bottom: 1.25rem;
    }
  }
}
</style>